import axios from 'axios'

let error = console.error

const api = '/categories'

export function getTrees (cb, fcb = () => error('getTrees')) {
  axios.get(api).then(res => {
    let data = replaceName(res.data)
    let obj = {
      'id': null,
      'title': '所有分类',
      'children': data
    }
    let initData = []
    initData.push(obj)
    cb(initData)
  }).catch(error => {
    fcb(error)
  })
}

export function addCategory (params, cb, fcb = () => error('addCategory')) {
  axios.post(api, params).then(res => {
    let data = res.data
    cb(data)
  }).catch(error => {
    fcb(error)
  })
}

export function editCategory (params, cb, fcb = () => error('editCategory')) {
  axios.put(api, params).then(res => {
    let data = res.data
    cb(data)
  }).catch(error => {
    fcb(error)
  })
}

export function delCategory (id, cb, fcb = () => error('delCategory')) {
  axios.delete(api + '/' + id).then(res => {
    let data = res.data
    cb(data)
  }).catch(error => {
    fcb(error)
  })
}

export function children (pid, cb, fcb = () => error('children')) {
  axios.get(api + '/' + pid).then(res => {
    let data = res.data
    cb(data)
  }).catch(error => {
    fcb(error)
  })
}

function replaceName (data) {
  data.filter(data => data.id !== null).map(value => {
    value.title = value.name
    nestLoop(value)
  })
  return data
}

function nestLoop (array) {
  if (array.children.length > 0) {
    replaceName(array.children)
  }
}
